#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Git配置脚本
功能：自动配置Git用户信息
"""

import os
import subprocess
import sys
import platform

def print_with_color(text, color="default"):
    """打印带颜色的文本"""
    colors = {
        "red": "\033[91m",
        "green": "\033[92m",
        "yellow": "\033[93m",
        "blue": "\033[94m",
        "default": "\033[0m"
    }
    
    # Windows系统不支持ANSI颜色代码，直接打印文本
    if platform.system() == "Windows":
        print(text)
    else:
        print(f"{colors.get(color, colors['default'])}{text}{colors['default']}")

def run_command(command):
    """运行命令并返回结果"""
    print_with_color(f"执行命令: {' '.join(command)}", "blue")
    try:
        result = subprocess.run(
            command,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True,
            shell=platform.system() == "Windows"  # Windows需要shell=True
        )
        if result.returncode == 0:
            print_with_color("✅ 命令执行成功", "green")
            if result.stdout.strip():
                print_with_color(f"输出: {result.stdout.strip()}", "cyan")
            return True, result.stdout
        else:
            print_with_color(f"❌ 命令执行失败 (返回码: {result.returncode})", "red")
            if result.stderr.strip():
                print_with_color(f"错误: {result.stderr.strip()}", "red")
            elif result.stdout.strip():
                print_with_color(f"输出: {result.stdout.strip()}", "yellow")
            return False, None
    except Exception as e:
        print_with_color(f"❌ 执行命令时出错: {str(e)}", "red")
        return False, None

def check_git_installed():
    """检查Git是否已安装"""
    print_with_color("\n=== 检查Git安装状态 ===", "blue")
    if platform.system() == "Windows":
        success, _ = run_command(["where", "git"])
    else:
        success, _ = run_command(["which", "git"])
    
    if not success:
        print_with_color("\n❌ Git未安装，请先安装Git！", "red")
        print_with_color("Windows用户可以从 https://git-scm.com/downloads 下载安装", "yellow")
        print_with_color("Linux用户可以使用包管理器安装，如: sudo apt install git", "yellow")
        return False
    
    # 检查Git版本
    success, output = run_command(["git", "--version"])
    if success:
        print_with_color(f"Git版本: {output.strip()}", "green")
    return success

def config_git(name, email, password=None):
    """
    配置Git用户信息
    
    参数:
        name: Git用户名
        email: Git邮箱
        password: Git密码（可选）
    """
    print_with_color("\n=== 配置Git用户信息 ===", "blue")
    
    # 配置用户名
    success, _ = run_command(["git", "config", "--global", "user.name", name])
    if not success:
        return False
    
    # 配置邮箱
    success, _ = run_command(["git", "config", "--global", "user.email", email])
    if not success:
        return False
    
    # 配置凭据存储（可选）
    if password:
        print_with_color("\n=== 配置Git凭据存储 ===", "blue")
        if platform.system() == "Windows":
            # Windows使用Windows凭据管理器
            success, _ = run_command(["git", "config", "--global", "credential.helper", "wincred"])
        elif platform.system() == "Darwin":  # macOS
            # macOS使用Keychain
            success, _ = run_command(["git", "config", "--global", "credential.helper", "osxkeychain"])
        else:  # Linux
            # Linux可以使用缓存或其他凭据存储
            success, _ = run_command(["git", "config", "--global", "credential.helper", "cache"])
        
        # 注意：脚本不会直接存储密码，Git会在首次需要时提示输入
        print_with_color("提示: Git将在首次需要时提示输入密码，然后会根据配置的凭据助手进行存储", "yellow")
    
    # 显示当前的Git配置
    print_with_color("\n=== 当前Git配置信息 ===", "blue")
    run_command(["git", "config", "--global", "--list"])
    
    return True

def main():
    """主函数"""
    print_with_color("======================================", "green")
    print_with_color("         Git配置脚本         ", "green")
    print_with_color("======================================", "green")
    
    # 配置信息
    GIT_NAME = "renovate_dream_0"
    GIT_EMAIL = "shenwenlong66@outlook.com"
    GIT_PASSWORD = "Wyhjxj666"  # 注意：实际使用中不建议硬编码密码
    
    # 检查Git是否已安装
    if not check_git_installed():
        return 1
    
    # 配置Git
    if config_git(GIT_NAME, GIT_EMAIL, GIT_PASSWORD):
        print_with_color("\n======================================", "green")
        print_with_color("🎉 Git配置完成！", "green")
        print_with_color(f"用户名: {GIT_NAME}", "green")
        print_with_color(f"邮箱: {GIT_EMAIL}", "green")
        print_with_color("======================================", "green")
        return 0
    else:
        print_with_color("\n❌ Git配置失败！", "red")
        return 1

if __name__ == "__main__":
    sys.exit(main())